import 'package:auto_route/auto_route.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/service/tuya_service.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/conform_dialog.dart';
import 'package:casdon/modules/device/application/notification/device_share_notifier.dart';
import 'package:casdon/modules/me/ui/widgets/circle_avatar_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:tuya_home_sdk_flutter/tuya_home_sdk_flutter.dart';

@RoutePage()
class DeviceShareListScreen extends ConsumerStatefulWidget {
  final String devId;
  final bool isFromNative;
  const DeviceShareListScreen({
    super.key,
    required this.devId,
    this.isFromNative = false,
  });

  @override
  ConsumerState<DeviceShareListScreen> createState() => _DeviceShareListState();
}

class _DeviceShareListState extends ConsumerState<DeviceShareListScreen> {
  bool? _hasShareRight;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _initShareRight();
    });
  }

  Future<void> _trySystemBackOrNative() async {
    try {
      const MethodChannel('native_to_flutter').invokeMethod('nativePop');
    } catch (_) {}
  }

  @override
  Widget build(BuildContext context) {
    final state = ref.watch(deviceMemberShareListNotifierProvider);
    return Scaffold(
      backgroundColor: Colors.grey[100],
      appBar: CommonAppBar(
        title: "分享",
        rightActions: [
          IconButton(
            icon: const Icon(Icons.add, color: Colors.black87),
            iconSize: 24,
            onPressed: _hasShareRight == true
                ? () async {
                    _showShareDialog();
                  }
                : null,
          ),
        ],
        onBack: () => _trySystemBackOrNative(),
      ),
      body: SafeArea(child: _buildBody(state)),
    );
  }

  Widget _buildBody(AsyncValue<List<ThingSmartShareMemberModel>> state) {
    if (_hasShareRight == null) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_hasShareRight == false) {
      return const Center(
        child: Text(
          '您无共享权限',
          style: TextStyle(fontSize: 16, color: Colors.black87),
        ),
      );
    }

    return state.when(
      loading: () => const Center(child: CircularProgressIndicator()),
      error: (error, _) => _buildErrorState(error),
      data: (members) => _buildMemberList(members),
    );
  }

  Future<void> _refreshMembers() {
    return ref
        .read(deviceMemberShareListNotifierProvider.notifier)
        .getMemberShareList(devId: widget.devId);
  }

  Widget _buildMemberList(List<ThingSmartShareMemberModel> members) {
    if (members.isEmpty) {
      return _buildEmptyState();
    }

    return RefreshIndicator(
      onRefresh: _refreshMembers,
      child: ListView.separated(
        physics: const AlwaysScrollableScrollPhysics(),
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
        itemCount: members.length,
        separatorBuilder: (_, __) => const SizedBox(height: 12),
        itemBuilder: (context, index) {
          return _buildSwipeActionItem(members[index]);
        },
      ),
    );
  }

  Widget _buildSwipeActionItem(ThingSmartShareMemberModel member) {
    return Dismissible(
      key: ValueKey('${member.memberId}_${member.uid}'),
      direction: DismissDirection.endToStart,
      background: const SizedBox.shrink(),
      secondaryBackground: _buildDeleteBackground(),
      confirmDismiss: (_) => _confirmDeleteMember(member),
      child: _buildContactItem(member),
    );
  }

  Widget _buildDeleteBackground() {
    return Container(
      alignment: Alignment.centerRight,
      decoration: BoxDecoration(
        color: Colors.redAccent,
        borderRadius: BorderRadius.circular(12),
      ),
      padding: const EdgeInsets.symmetric(horizontal: 20),
      child: const Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(Icons.delete_outline, color: Colors.white, size: 22),
          SizedBox(width: 6),
          Text(
            '删除',
            style: TextStyle(
              color: Colors.white,
              fontSize: 14,
              fontWeight: FontWeight.w600,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyState() {
    return RefreshIndicator(
      onRefresh: _refreshMembers,
      child: ListView(
        physics: const AlwaysScrollableScrollPhysics(),
        padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 80),
        children: const [
          Icon(Icons.share_outlined, size: 48, color: Colors.grey),
          SizedBox(height: 16),
          Text(
            '暂时没有共享成员',
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: 16, color: Colors.black87),
          ),
          SizedBox(height: 8),
          Text(
            '点击右上角即可邀请成员共享此设备。',
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: 14, color: Colors.black54),
          ),
        ],
      ),
    );
  }

  Widget _buildErrorState(Object error) {
    return Center(
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 32),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(Icons.error_outline, size: 48, color: Colors.redAccent),
            const SizedBox(height: 16),
            const Text(
              '加载共享成员失败',
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
            ),
            const SizedBox(height: 8),
            Text(
              error.toString(),
              textAlign: TextAlign.center,
              style: const TextStyle(fontSize: 14, color: Colors.black54),
            ),
            const SizedBox(height: 24),
            ElevatedButton(
              onPressed: () {
                _refreshMembers();
              },
              child: const Text('重试'),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildContactItem(ThingSmartShareMemberModel model) {
    final displayName = _memberDisplayName(model);
    final shareModeText = model.shareMode == ThingShareValidationType.forever
        ? '长期共享'
        : '临时共享';

    return Container(
      margin: EdgeInsets.zero,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: ListTile(
        leading: CircleAvatarButton(
          imageUrl: model.iconUrl,
          defaultImage: AssetImage(Assets.images.icAvatar.path),
          size: 48.w,
          onPressed: () {},
        ),
        title: Text(
          displayName,
          style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
        ),
        subtitle: Text(
          model.userName,
          style: TextStyle(fontSize: 14, color: Colors.grey[600]),
        ),
      ),
    );
  }

  Future<bool?> _confirmDeleteMember(ThingSmartShareMemberModel member) async {
    final name = _memberDisplayName(member);
    final confirmed = await showConfirmDialog(
      context: context,
      content: '确定要删除$name的共享权限吗？',
      confirmText: '删除',
      cancelText: '取消',
    );

    if (!confirmed) {
      return false;
    }

    final success = await ref
        .read(deviceMemberShareListNotifierProvider.notifier)
        .removeMemberShare(memberId: member.memberId);

    if (mounted) {
      _showSnackBar(success ? '删除成功' : '删除失败，请稍后再试');
    }

    return success;
  }

  void _showSnackBar(String message) {
    if (!mounted) return;
    ScaffoldMessenger.of(context)
      ..hideCurrentSnackBar()
      ..showSnackBar(
        SnackBar(content: Text(message), behavior: SnackBarBehavior.floating),
      );
  }

  String _memberDisplayName(ThingSmartShareMemberModel model) {
    final displayName =
        (model.nickName.isNotEmpty ? model.nickName : model.userName).trim();
    if (displayName.isNotEmpty) {
      return displayName;
    }
    return model.userName.isNotEmpty ? model.userName : '共享成员';
  }

  Future<void> _showShareDialog() async {
    final result = await showInputDialog(
      context: context,
      title: '共享设备',
      hintText: '输入被共享的账号',
    );
    if (result != null && result.isNotEmpty) {
      final success = await ref
          .read(deviceMemberShareListNotifierProvider.notifier)
          .addMemberShare(devId: widget.devId, userAccount: result.trim());
      if (success && mounted) {
        _refreshMembers();
        _showSnackBar('已发送共享邀请');
      } else if (mounted) {
        _showSnackBar('共享失败，请稍后再试');
      }
    }
  }

  Future<bool> _isHaveShareRight() async {
    final devModel = await TuyaService().getDeviceById(devId: widget.devId);
    if (devModel == null) {
      return false;
    }
    // isShare == true 表示当前用户是被共享成员，无再次共享权限
    return !devModel.isShare;
  }

  Future<void> _initShareRight() async {
    final hasRight = await _isHaveShareRight();
    if (!mounted) return;
    setState(() {
      _hasShareRight = hasRight;
    });
    if (hasRight) {
      await _refreshMembers();
    }
  }
}
